/**
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;

/**
 * spring工具类
 * @author limk
 * @date 2018年2月12日 下午6:15:53
 * @version 1.0
 */
public class SpringUtils implements ApplicationContextAware {

	private static ApplicationContext context;

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		SpringUtils.context = context;
	}

	public static <T> T getBean(Class<T> clazz){
		if (clazz == null) {
			return null;
		}
		return context.getBean(clazz);
	}
	
	@SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName){
	    if (null == beanName || "".equals(beanName.trim())) {
            return null;
        }
	    return (T) context.getBean(beanName);
	}

	public static <T> T getBean(String beanName, Class<T> clazz) {
		if (null == beanName || "".equals(beanName.trim())) {
			return null;
		}
		if (clazz == null) {
			return null;
		}
		return context.getBean(beanName, clazz);
	}

	public static ApplicationContext getContext(){
		if (context == null) {
			return null;
		}
		return context;
	}

	public static void publishEvent(ApplicationEvent event) {
		if (context == null) {
			return;
		}
		context.publishEvent(event);
	}

}
